package logic

import (
	"context"
	"encoding/json"
	"manuscript-service/bookrpc/bookrpc"
	"manuscript-service/bookrpc/internal/svc"
	"manuscript-service/model/cache"
	"manuscript-service/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 稿件列表
func (l *BookListLogic) BookList(in *bookrpc.BookListRequest) (*bookrpc.BookListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*bookrpc.BookList

	cacheData, _ := cache.Rdb.Get(cache.Ctx, "bookList").Result()
	if cacheData == "" {
		list = mysql.BookList(mysql.DB)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, "bookList", jsonData, time.Minute*120)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	return &bookrpc.BookListResponse{
		List: list,
	}, nil
}
